// ==UserScript==
// @name         微信读书自动阅读
// @namespace    https://gitee.com/bluesword12350/web-script
// @version      1.3.1
// @description  微信读书自动阅读（只有从书架进入才能自动阅读，且只阅读书架中不公开的书籍）
// @author       李林峰
// @match        https://weread.qq.com/web/reader/*
// @match        https://weread.qq.com/web/shelf
// @updateURL    https://gitee.com/bluesword12350/web-script/raw/master/tampermonkey/sword-weread.js
// @downloadURL  https://gitee.com/bluesword12350/web-script/raw/master/tampermonkey/sword-weread.js
// @icon         //
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

(() => {
  'use strict';
  let _handler;
  //页面滚动时间间隔
  const _page_scroll_interval = 5000;
  //翻页等待时间间隔
  const _page_turn_interval = 3000;
  //每次页面滚动距离
  const _page_scroll_distance = 24;

  const bookURLPattern = new URLPattern("https://weread.qq.com/web/reader/:bookId");
  const autoReadBooksKey = "autoReadBooks";
  const autoReadBooks = GM_getValue(autoReadBooksKey, [])

  //重新获取页面元素
  let title, chapter, l_h, page_pos, scroll_enabled;

  function fetchPageElement() {
    try {
      title = document.getElementsByClassName("readerTopBar_title_chapter")[0].innerText;
      chapter = document.getElementsByClassName("readerTopBar_title_link")[0].innerText;
    } catch (err) {
      title = "获取标题失败";
      chapter = "微信自动阅读";
    }
    let app = document.getElementById("app");
    l_h = app.scrollHeight - app.clientHeight;
    scroll_enabled = true;
    page_pos = 0;
  }

  //滚动事件
  function onScroll() {
    if (!scroll_enabled) return;
    if (page_pos < l_h) {
      page_pos += _page_scroll_distance;
      const progress = (Math.min(page_pos / l_h, 1) * 100).toFixed(2) + "%";
      document.title = `${progress}【${chapter} ${title}】`;
      scroll(0, page_pos);
      return;
    }
    scroll_enabled = false;
    if (document.getElementsByClassName("readerFooter_button")[0]) {
      document.body.ownerDocument.dispatchEvent(new KeyboardEvent("keydown", {keyCode: 39}));
      setTimeout(() => fetchPageElement(), _page_turn_interval);
    } else {
      document.title = `已读完【${chapter}】`;
      clearInterval(_handler);
      readNext()
    }
  }

  function autoRead() {
    let notAutoRead = true;
    let currentUrl = window.location.href;
    for (let autoReadBook of autoReadBooks) {
      // noinspection JSUnresolvedReference
      if (currentUrl.startsWith(autoReadBook) || autoReadBook.startsWith(currentUrl)) {
        notAutoRead = false;
        break;
      }
    }
    if (notAutoRead) {
      console.log("当前页面不在自动阅读范围内，自动阅读已关闭", currentUrl)
      console.log("自动阅读目录", autoReadBooks)
      return;
    }
    fetchPageElement();
    document.title = `开始自动阅读【${chapter}】`
    _handler = setInterval(onScroll, _page_scroll_interval);
    autoReadBooks.shift();
    GM_setValue(autoReadBooksKey, autoReadBooks)
    setTimeout(readNext, 5 * 60 * 1000)
  }

  function readNext(){
    if (autoReadBooks[0]) {
      window.location.replace(autoReadBooks[0])
    } else {
      window.location.replace("https://weread.qq.com/web/shelf")
    }
  }

  function autoReadList() {
    let needAutoReadBooks = [];
    for (let shelfBook of document.getElementsByClassName("shelfBook")) {
      if (shelfBook.getElementsByClassName("wr_bookCover_privateTag")[0]) {
        needAutoReadBooks.push(shelfBook.href);
      }
    }
    if (needAutoReadBooks.length <= 0) {
      return;
    }
    for (let i = autoReadBooks.length - 1; i >= 0; i--) {
      if (!needAutoReadBooks.includes(autoReadBooks[i])) {
        autoReadBooks.splice(i, 1);
      }
    }
    if (autoReadBooks.length <= 0) {
      autoReadBooks.push(...needAutoReadBooks);
    }
    GM_setValue(autoReadBooksKey, autoReadBooks)
    readNext()
  }

  function exec() {
    if (window.location.href === "https://weread.qq.com/web/shelf") {
      autoReadList()
    } else if (bookURLPattern.exec(window.location.href)) {
      autoRead()
    }
  }

  exec();
})();